import config from '@/utils/config/index.js'
import { notice } from '@/utils/common.js'

const uuid = require('uuid')

//配置
const rqConfig = {
	baseUrl: config.baseUrl,
	timeout: 60000,
}

//响应拦截
const responseIntercept = function(response) {	
	const data = response.data
	data.code = parseInt(data.code)
	return data
}

//请求拦截
const requestIntercept = function(transFlag) {
	let authToken = uni.getStorageSync("_app_token")
	let username = uni.getStorageSync("userAccount")
	let lang = uni.getLocale()
	if(lang == 'zh-Hans') {
		lang = 'zh-cn'
	} else if(lang == 'en') {
		lang = 'en-us'
	}
	let header = {
		'X-Authorization-access_token': authToken,
		'username'					  : username,
		'lang'						  : lang
	}
	if(transFlag) {
		header.transFlag = true
		header['CP-message-id'] = uuid()
		header['CP-transaction-id'] = uuid()
	}
	return { header }
}

//请求
const service = {
	_basis(opt, success, fail) {
		if(uni.getStorageSync("baseUrl")) {
			rqConfig.baseUrl = uni.getStorageSync("baseUrl")
		}
		
		const defaultOption = {
			loading : true,
			showFailMsg : true
		}
		
		const nOption = opt ? Object.assign(defaultOption , opt) : defaultOption;
		
		let {
			url,
			params,
			method,
			pager,
			type,
			urlType,
			paramType
		} = nOption
		
		let data = {}

		if(pager && type) {
			data.requestPage = {
				limit: pager.limit,
				pageNo: pager.start
			}
		}else if(pager){
			params = Object.assign(params || {}, {
				pageSize: pager.limit,
				pageNo: pager.start
			})
		}

		if (params) {
			if(paramType != 'post'){
				let parameter = ''
				for (const name in params) {
					if(params[name] !== undefined && params[name] !== null)
						parameter += `&${name}=${params[name]}`;
				}
				
				if (parameter !== '') {
					parameter = parameter.substr(1);
					url += url.includes('?') ? '' : '?' + parameter;
				}
			}
			
			if(type){
				data.parameters = params
			}else{
				data = params
			}
		}

		const enableLoading = getApp() && !getApp().globalData.disableLoading;
		
		if (enableLoading && nOption.loading) {	
			notice.showLoading();
		}
		
		const requestOpt = {
			url: `${rqConfig.baseUrl}${url}`,
			data,
			method,
			success: (res) => {
				if (enableLoading && nOption.loading) {
					notice.hideLoading();
				}
				
				const resData = responseIntercept(res);
				
				//DBUGE调试
				// console.log('%c 请求api: ' + url,'color:red');
				// console.log('%c 返回值: ' ,'color:red' , resData);
				
				if(!resData){
					return;
				} 
				if(resData.state === 200 || resData.code === 0) {
					success && success(resData);
				} else if(resData.state === 6020301 || resData.code === 6020301) {
					notice.toast("登录信息已过期，请重新登录");
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/platform/login/index'
						})
					}, 500)
				} else {
					let errMsg = "网络异常，请稍后再试"
					if(resData && (resData.message || resData.cause)) {
						errMsg = resData.message ? resData.message : resData.cause
					}
					if(nOption.showFailMsg) {
						notice.toast(errMsg);
					}
					fail && fail(errMsg)
				}
			},
			fail: (res) => {
				if (enableLoading && nOption.loading) {
					notice.hideLoading();
				}
				notice.toast(res);	
			}
		}
		return uni.request(Object.assign(requestOpt, requestIntercept(params ? params.transFlag : false)));
	},
	post(opt) {
		opt.method = 'POST'
		// let result = new Promise((resolve, reject) => {
		// 	this._basis(opt, resolve, reject)
		// })
		// result.catch(err => {
		// 	if(err.code === 12) {
		// 		notice.toast('接口地址配置错误！')
		// 	}
		// 	return
		// })
		// return result
		
		return new Promise((resolve, reject) => {
			this._basis(opt, resolve, reject)
		})
	},
	get(opt) {
		opt.method = 'GET'
		// let result = new Promise((resolve, reject) => {
		// 	this._basis(opt, resolve, reject)
		// })
		// result.catch(err => {
		// 	if(err.code === 12) {
		// 		notice.toast('接口地址配置错误！')
		// 	}
		// 	return
		// })
		// return result
		
		return new Promise((resolve, reject) => {
			this._basis(opt, resolve, reject)
		})
	},
	common(opt) {
		return new Promise((resolve, reject) => {
			this._basis(opt, resolve, reject)
		})
	}
}

export default service